package com.school.common.util;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringUtils {
	private static Logger logger = Logger.getLogger(SpringUtils.class);

	private static ApplicationContext ctx = null;

	/**
	 * 构造函数
	 * 
	 */
	public SpringUtils() {

	}

	// 初始化文件
	private synchronized static void initData() {

		if (ctx != null) {
			return;
		}

		try {
			/*
			URL path = SpringUtils.class.getResource("/");
			String dir = path.getPath();
			int index = dir.indexOf("\\WEB-INF\\");
			if (index < 0) {
				index = dir.indexOf("/WEB-INF/");
			}
			dir = dir.substring(0, index + 8);
			if ("/".equalsIgnoreCase(File.separator)) {
				dir = dir.replace("\\", "/");
				if (dir.startsWith("/")) {
					dir = File.separator + dir;
				}
			} else {
				dir = dir.replace("/", "\\");
				if (dir.startsWith("\\")) {
					dir = dir.substring(1);
				}
			}*/
			ctx = new FileSystemXmlApplicationContext("classpath:../spring.xml");

		} catch (Exception ex) {
			ctx = null;
			logger.error("加载spring文件错误。" + ex.getMessage());
			ex.printStackTrace();
		}
	}

	public static Object getBean(String id) {
		if (ctx == null) {
			initData();
		}
		Object obj = ctx.getBean(id);
		return obj;
	}

	public static void setServletContext(ServletContext servletContext) {

		logger.info("set servlet context from web");

		ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

	}
}
